package com.lanou.managerLogin.book.dao;

import com.lanou.managerLogin.book.domain.Book;
import com.lanou.managerLogin.category.domain.Category;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDaoImpl implements BookDao {

    private ComboPooledDataSource dataSource = new ComboPooledDataSource();

    @Override
    public List<Book> bookList() {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            List<Book> query = qr.query(conn, "select * from book join category on book.cid = category.cid", new BeanListHandler<Book>(Book.class));
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public Book oneBookInfo(String bid) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            Book query = qr.query(conn, "select * from book where bid = ?", new BeanHandler<Book>(Book.class), bid);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new Book();
    }

    @Override
    public String findCnameByCid(String cid){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            String sql = "select cname from category where cid = ? ";
            QueryRunner runner = new QueryRunner();
            Category category = runner.query(conn, sql, new BeanHandler<Category>(Category.class), cid);
            String cName = category.getCname();
            return cName;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void deleteOneBook(String bid) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            qr.update(conn, "delete from book where bid = ?", bid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertBook(Book book){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            String sql = "insert into book values(?,?,?,?,?,?)";
            QueryRunner runner = new QueryRunner();
            runner.update(conn, sql, book.getBid(),book.getBname(),book.getPrice(),book.getAuthor(),book.getImage(),book.getCid());
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
